import { reqCartList, reqDeleteCartById,reqUpdatateCheckByid } from "@/api"

const actions = {
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  async getCartByskuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //购物车选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdatateCheckByid(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  deleteAllcheckedCart({ dispatch, getters }) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('getCartByskuId', item.skuId) : ''
      PromiseAll.push(promise)
    });
    return Promise.all(PromiseAll)
  },
  //全选状态
  sendFullSelectionStatus({ dispatch, state }, checked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked: checked })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }

}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const state = {
  cartList: []
}

const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  }
}

export default {
  namespaced: true,
  actions,
  mutations,
  state,
  getters
}